<template>
  <div class="community-list">
    <div class="page-header">
      <div class="header-content">
        <h2>社区列表</h2>
        <p class="header-subtitle">管理系统中的所有社区信息</p>
      </div>
      <button class="add-btn" @click="showAddDialog">
        <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
          <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
        </svg>
        添加社区
      </button>
    </div>

    <div class="list-container">
      <div class="table-header">
        <div class="search-box">
          <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
            <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
          </svg>
          <input 
            v-model="searchKeyword" 
            placeholder="搜索社区名称..." 
            class="search-input"
          />
        </div>
      </div>
      
      <div v-if="loading" class="loading">
        <div class="spinner"></div>
        <span>加载中...</span>
      </div>
      <div v-else-if="filteredCommunityList.length === 0" class="empty-state">
        <svg viewBox="0 0 24 24" width="48" height="48" fill="currentColor">
          <path d="M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-6 0h-4V4h4v2z"/>
        </svg>
        <p>暂无社区数据</p>
      </div>
      <table v-else>
        <thead>
          <tr>
            <th>社区名称</th>
            <th>地址</th>
            <th>联系人</th>
            <th>联系电话</th>
            <th>老人数量</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in paginatedCommunityList" :key="item.communityId">
            <td>
              <div class="community-name">
                <div class="community-icon">
                  <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                    <path d="M12 5.69l5 4.5V18h-2v-6H9v6H7v-7.81l5-4.5M12 3L2 12h3v8h6v-6h2v6h6v-8h3L12 3z"/>
                  </svg>
                </div>
                {{ item.name }}
              </div>
            </td>
            <td>{{ item.address }}</td>
            <td>{{ item.contactPerson }}</td>
            <td>{{ item.contactPhone }}</td>
            <td>
              <span class="elder-count">{{ item.elderCount }}</span>
            </td>
            <td>
              <span :class="['status-tag', item.status]">
                {{ item.status === 'active' ? '正常' : '禁用' }}
              </span>
            </td>
            <td>{{ item.createTime }}</td>
            <td>
              <div class="action-buttons">
                <button class="edit-btn" @click="showEditDialog(item)">
                  <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor">
                    <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
                  </svg>
                  编辑
                </button>
                <button class="delete-btn" @click="handleDelete(item.communityId)">
                  <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor">
                    <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                  </svg>
                  删除
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      
      <!-- 分页 -->
      <div class="pagination" v-if="filteredCommunityList.length > 0">
        <button 
          :disabled="currentPage === 1" 
          @click="currentPage--"
          class="pagination-btn"
        >
          <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
            <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
          </svg>
        </button>
        <span class="page-info">
          第 {{ currentPage }} / {{ totalPages }} 页
        </span>
        <button 
          :disabled="currentPage === totalPages" 
          @click="currentPage++"
          class="pagination-btn"
        >
          <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
            <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
          </svg>
        </button>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <div class="dialog-overlay" v-if="showDialog" @click="closeDialog">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>{{ isEdit ? '编辑社区' : '添加社区' }}</h3>
          <button class="close-btn" @click="closeDialog">
            <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
              <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
            </svg>
          </button>
        </div>
        <form @submit.prevent="handleSubmit">
          <div class="form-item">
            <label>社区名称：</label>
            <input v-model="formData.name" required />
          </div>
          <div class="form-item">
            <label>地址：</label>
            <input v-model="formData.address" required />
          </div>
          <div class="form-item">
            <label>联系人：</label>
            <input v-model="formData.contactPerson" required />
          </div>
          <div class="form-item">
            <label>联系电话：</label>
            <input v-model="formData.contactPhone" required />
          </div>
          <div class="form-item">
            <label>状态：</label>
            <select v-model="formData.status" required>
              <option value="active">正常</option>
              <option value="inactive">禁用</option>
            </select>
          </div>
          <div class="form-item">
            <label>描述：</label>
            <textarea v-model="formData.description"></textarea>
          </div>
          <div class="dialog-footer">
            <button type="button" class="cancel-btn" @click="closeDialog">取消</button>
            <button type="submit" class="submit-btn">确定</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import request from '../../utils/request'

const loading = ref(true)
const communityList = ref([])
const showDialog = ref(false)
const isEdit = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

const formData = ref({
  communityId: null,
  name: '',
  address: '',
  contactPerson: '',
  contactPhone: '',
  elderCount: 0,
  description: '',
  status: 'active'
})

// 计算过滤后的社区列表
const filteredCommunityList = computed(() => {
  if (!searchKeyword.value) {
    return communityList.value
  }
  return communityList.value.filter(item => 
    item.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(filteredCommunityList.value.length / pageSize.value)
})

// 计算当前页数据
const paginatedCommunityList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredCommunityList.value.slice(start, end)
})

// 获取社区列表
const getCommunityList = async () => {
  try {
    const res = await request.get('/admin/getCommunityList')
    communityList.value = res.data
  } catch (error) {
    console.error('获取社区列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  formData.value = {
    communityId: null,
    name: '',
    address: '',
    contactPerson: '',
    contactPhone: '',
    elderCount: 0,
    description: '',
    status: 'active'
  }
  showDialog.value = true
}

// 显示编辑对话框
const showEditDialog = (community) => {
  isEdit.value = true
  formData.value = { ...community }
  showDialog.value = true
}

// 关闭对话框
const closeDialog = () => {
  showDialog.value = false
}

// 提交表单
const handleSubmit = async () => {
  console.log('提交的表单数据:', formData.value)
  try {
    if (isEdit.value) {
      await request.put('/admin/updateCommunity', formData.value)
    } else {
      await request.post('/admin/addCommunity', formData.value)
    }
    await getCommunityList()
    closeDialog()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 删除社区
const handleDelete = async (id) => {
  if (confirm('确定要删除该社区吗？')) {
    try {
      await request.delete(`/admin/deleteCommunity/${id}`)
      await getCommunityList()
      // 如果当前页没有数据了，回到上一页
      if (paginatedCommunityList.value.length === 0 && currentPage.value > 1) {
        currentPage.value--
      }
    } catch (error) {
      console.error('删除失败:', error)
    }
  }
}

onMounted(() => {
  getCommunityList()
})
</script>

<style scoped>
.community-list {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 24px;
}

.header-subtitle {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 16px;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: #fff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(79, 172, 254, 0.3);
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.4);
}

.list-container {
  background: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 6px;
  padding: 8px 12px;
  width: 300px;
  border: 1px solid #e9ecef;
}

.search-box svg {
  color: #6c757d;
  margin-right: 8px;
}

.search-input {
  flex: 1;
  border: none;
  background: transparent;
  outline: none;
  font-size: 14px;
}

.search-input::placeholder {
  color: #adb5bd;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

th, td {
  padding: 16px 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

th {
  background: #fafafa;
  font-weight: 600;
  color: #495057;
  font-size: 14px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.community-name {
  display: flex;
  align-items: center;
  font-weight: 500;
}

.community-icon {
  margin-right: 8px;
  color: #4facfe;
}

.elder-count {
  display: inline-block;
  padding: 2px 8px;
  background: #e3f2fd;
  color: #1976d2;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag.active {
  background: #e8f7ef;
  color: #28a745;
}

.status-tag.inactive {
  background: #f8f0f1;
  color: #dc3545;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s ease;
}

.edit-btn {
  background: #e3f2fd;
  color: #1976d2;
}

.edit-btn:hover {
  background: #bbdefb;
}

.delete-btn {
  background: #f8f0f1;
  color: #dc3545;
}

.delete-btn:hover {
  background: #f5c6cb;
}

/* 加载状态 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #6c757d;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #e9ecef;
  border-top: 3px solid #4facfe;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #6c757d;
}

.empty-state svg {
  color: #ced4da;
  margin-bottom: 16px;
}

.empty-state p {
  margin: 0;
  font-size: 16px;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  padding: 20px 0;
}

.pagination-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: 1px solid #dee2e6;
  background: #fff;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.pagination-btn:hover:not(:disabled) {
  background: #4facfe;
  border-color: #4facfe;
  color: #fff;
}

.pagination-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.page-info {
  color: #495057;
  font-size: 14px;
  font-weight: 500;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background: #fff;
  padding: 0;
  border-radius: 12px;
  width: 500px;
  max-width: 90vw;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 25px rgba(0,0,0,0.2);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  color: #6c757d;
  transition: background 0.2s ease;
}

.close-btn:hover {
  background: #f1f3f4;
}

.form-item {
  margin-bottom: 20px;
  padding: 0 24px;
}

.form-item label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #495057;
}

.form-item input,
.form-item select,
.form-item textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ced4da;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s ease;
  box-sizing: border-box;
}

.form-item input:focus,
.form-item select:focus,
.form-item textarea:focus {
  outline: none;
  border-color: #4facfe;
  box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
}

.form-item textarea {
  height: 100px;
  resize: vertical;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  border-top: 1px solid #eee;
}

.dialog-footer button {
  padding: 8px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s ease;
}

.cancel-btn {
  border: 1px solid #ced4da;
  background: #fff;
  color: #495057;
}

.cancel-btn:hover {
  background: #f8f9fa;
}

.submit-btn {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: #fff;
  border: none;
  box-shadow: 0 2px 6px rgba(79, 172, 254, 0.3);
}

.submit-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.4);
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .table-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .search-box {
    width: 100%;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  th, td {
    padding: 12px 8px;
    font-size: 13px;
  }
  
  .dialog {
    width: 95vw;
  }
}
</style>